package Inet;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.HashMap;

//服务器端
public class UdpEchoServer_Dic {
    //Server是创建
    private DatagramSocket socket = null;
    private HashMap<String,String> dict = null;
    //构造方法 服务器端要传一个端口号
    public UdpEchoServer_Dic(int port) throws SocketException {
        socket = new DatagramSocket(port);

        dict = new HashMap<>();
        dict.put("cat","小猫");
        dict.put("dog","小狗");
        dict.put("duck","小鸭");
        dict.put("pig","小猪");
        dict.put("fish","小鱼");
    }

    //构建 start方法，服务器的主体
    public void start() throws IOException {
        System.out.println("服务器启动！");
        while (true) {
            //1、读取请求并解析
            DatagramPacket requestpacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestpacket);
            String request = new String(requestpacket.getData(),0,requestpacket.getLength());

            //2、根据请求计算响应
            String repsonse = process(request);
            //3、把响应写回到客户端
            DatagramPacket responsePacket = new DatagramPacket(repsonse.getBytes(),0,repsonse.getBytes().length
                                                                ,requestpacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s:%d] req = %s, resp = %s",requestpacket.getSocketAddress(),requestpacket.getPort(),request,repsonse);
            System.out.println();
        }
    }

    private String process(String request) {
        return dict.getOrDefault(request,"词典里没有该词汇");
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer_Dic dic = new UdpEchoServer_Dic(1010);
        dic.start();
    }

}
